import stepper from '../stepper/stepper.vue';
import goodsCombo from '../goods-combo/goods-combo.vue';

import {
	debounce
} from '@/common/js/util.js';

export default {
	name: 'SingleSelect',
	components: {
		stepper,
		goodsCombo
	},
	props: {

	},
	data() {
		return {
			originTotalPrice: 0,
			totalPrice: 0, // 此产品总价：(售卖价格 + 加价价格) * 数量 ：： 显示用
			useCouponUpsetPrice: 0, // 用券后的起始价
			useCouponTotalPrice: 0, // 用券后的总价
			num: 1, // 产品数量
			relevanceProducts: {}, // 关联的产品对象
			relevanceMutexIds: {}, // 映射互斥id对象数组 
			relevanceSelects: [], // 关联产品选择信息
			shuxingConfig: {}, // 属性配置
			shuxingValue: '', // 选择属性的值
			isReplaceNum: false, // 是否替换数量
		};
	},
	computed: {
		// 是否显示弹窗
		isShowSinglePop() {
			return this.$store.state.isShowSinglePop;
		},

		// 产品信息
		product() {
			const {
				product
			} = this.$store.state.singleProductInfo;
			return product;
		},

		// 产品券id
		couponId() {
			const {
				couponId
			} = this.$store.state.singleProductInfo;
			return couponId || '';
		}

	},
	watch: {
		isShowSinglePop(val) {
			if (val) {
				this.queryRelevanceProducts();
				this.initData();
			}
		}
	},
	methods: {
		// 初始化数据
		initData() {
			const product = this.product;
			const {
				basePrice,
				specialPrice,
				shuxing
			} = product;

			this.originTotalPrice = basePrice;
			this.totalPrice = basePrice;

			if (this.couponId) {
				this.useCouponUpsetPrice = specialPrice;
				this.useCouponTotalPrice = specialPrice;
			}

			// 属性
			const sx = shuxing ? shuxing[0] : '';
			if (sx) {
				const sxList = [];
				for (let key in sx) {
					if (key.indexOf('sx_type') > -1 && sx[key]) {
						sxList.push(sx[key]);
					}
				}
				this.shuxingConfig = {
					name: sx.sx_name,
					list: sxList
				}
			}

		},

		// 计算总价
		countTotalPrice() {
			const relevanceSelects = this.relevanceSelects;
			const _originPrice = Number((this.originTotalPrice * this.num).toFixed(2));
			let addPrice = 0;

			relevanceSelects.map(item => {
				if (item.num) {
					addPrice += (item.num * item.price)
				}
			});

			this.totalPrice = Number((_originPrice + (addPrice * this.num)).toFixed(2));
			this.useCouponTotalPrice = Number((this.useCouponUpsetPrice + (addPrice * this.num)).toFixed(2));

		},

		// 查询关联产品组
		queryRelevanceProducts() {
			const product = this.product;
			const buttonType = product.buttonType;
			const proId = product.id;
			const {
				relevanceMap,
				productsMap
			} = this.$store.state;

			// 初始关联产品元素
			const relevanceItems = {};

			// 关联产品(规格 | 搭配)
			let products = relevanceMap[`${proId}_2_1`] || [];
			products.map(item => {
				item.parentOpid = proId; // 关联产品对应的父产品id
				item.conKucun = 0;
				if (productsMap[item.productId]) {
					if(productsMap[item.productId].displayOrder < 0) {
						item.conKucun = -1;
					}
				}
			});
			if (products.length) {
				relevanceItems['gg'] = {
					productId: proId,
					options: products,
					comboInfo: {
						id: proId, // 组 id
						comboIdx: 0, // 组索引
						maxQty: 1, // 最大值
						minQty: 1, // 最小值
						isRadio: true, // 是否单选
						isRelevance: true, // 是否关联产品
						attr: 2, // 规格|搭配
						hasDefault: true, // 是否有默认值
					}
				}
			}


			// 关联产品(加量)
			if (relevanceMap[`${proId}_1_1`]) {
				let jl_products = relevanceMap[`${proId}_1_1`] || [];
				jl_products.map(item => {
					item.parentOpid = proId; // 关联产品对应的父产品id
					item.conKucun = 0;
					if (productsMap[item.productId]) {
						if(productsMap[item.productId].displayOrder < 0) {
							item.conKucun = -1;
						}
					}
				});
				relevanceItems['jl'] = {
					productId: proId,
					options: jl_products,
					comboInfo: {
						id: proId, // 组 id
						comboIdx: 0, // 组索引
						maxQty: jl_products.length, // 最大值
						minQty: 0, // 最小值
						isRadio: false, // 是否单选
						isRelevance: true, // 是否关联产品
						attr: 1, // 规格|搭配
						hasDefault: false, // 是否有默认值
					}
				}
			}

			// 所有关联的产品id
			const allPid = [];
			for (let key in relevanceItems) {
				let options = relevanceItems[key].options || [];
				options.map(x => {
					allPid.push(x.productId);
				});
			}

			for (let key in relevanceItems) {
				let CRP = relevanceItems[key];
				
				CRP.throughAllPid = allPid;
				
			}

			this.relevanceProducts = relevanceItems;

			if (!relevanceItems['gg'] && !relevanceItems['jl']) {
				let cartList = this.$store.state.cartList;
				let tempProducts = cartList.filter(item => item.productId === proId)[0];
				if (tempProducts) {
					this.num = tempProducts.productCount || 1;
					this.isReplaceNum = true;
				}
			}
		},

		// 选择的关联产品
		handleOptionSelects(data) {
			const {
				comboProducts,
				comboInfo,
				status
			} = data;
			const {
				comboIdx
			} = comboInfo;

			let relevanceSelects = this.relevanceSelects || [];

			if (relevanceSelects.length) {
				const portionDatas = relevanceSelects.filter(x => {
					let flag = !(comboProducts.some(y => {
						return (x.productId === y.productId) && (x.parentOpid === y.parentOpid);
					}));
					return flag;
				});
				relevanceSelects = portionDatas.concat(comboProducts);
			} else {
				relevanceSelects = comboProducts;
			}

			this.relevanceSelects = relevanceSelects;

			this.countTotalPrice();
		},

		// 处理互斥id事件
		handleRelevanceMutexEvent(data) {
			const {
				comboIdx,
				mutexIds
			} = data;
			this.$set(this.relevanceMutexIds, comboIdx, mutexIds);
		},

		// 选择属性
		onChooseSx(sx) {
			this.shuxingValue = sx;
		},

		// 点击了加号
		handleAdd() {
			this.num++;
			this.countTotalPrice();
		},

		// 点击了减号
		handleMinus() {
			if (this.num > 1) {
				this.num--;

				this.countTotalPrice();
			}
		},

		// 点击加入购物车
		onJoinCart: debounce(function() {
			const product = this.product;
			const buttonType = product.buttonType;
			const proId = product.id;
			const addConfig = this.addConfig;
			const relevanceProducts = this.relevanceProducts;
			const relevanceSelects = this.relevanceSelects;
			
			if (relevanceProducts['gg'] && !relevanceSelects.length){
				uni.showToast({
					title: '规格产品必选一个',
					icon: 'none',
					duration: 3000
				})
				return;
			}

			// 关联子产品
			let child = [];
			let addPrice = 0; // 关联产品加价价格
			let productDesc = ''; // 描述
			
			relevanceSelects.map((item, index) => {
				if (item.num) {
					child.push({
						taocanzuId: proId,
						productId: item.productId,
						productName: item.name,
						productCount: item.num,
						salePrice: item.price,
						parentOpid: item.parentOpid,
						isRelasionSale: "1"
					})
					addPrice += (item.num * item.price);
					productDesc += `${item.name} + `;
				}
			});

			let desc = productDesc.slice(0, -3);

			// 组合产品
			addPrice = Number(addPrice.toFixed(2));
			const {
				vipPrice,
				originPrice,
				basePrice
			} = product;

			const freePrice = Number((originPrice - basePrice).toFixed(2));
			const orinPrice = Number((originPrice + addPrice).toFixed(2));
			const salePrice = Number((basePrice + addPrice).toFixed(2));

			let comboProducts = {
				addPrice,
				boxFee: product.boxprice || 0,
				boxNum: 0,
				code: product.code,
				freePrice,
				isspecPrice: 0,
				orinPrice,
				productCount: this.num || 1,
				productId: product.id,
				productName: product.name,
				salePrice,
				specialPrice: product.specialPrice,
				vipPrice,
				//以下字段用于购物车展示，提交订单的时候会删掉它门
				img: product.images.middle,
				desc, //描述
				couponType: '' //券类型
			}
			comboProducts.child = child;

			if (this.couponId) {
				comboProducts.couponId = this.couponId;
			}

			if (this.shuxingValue) {
				comboProducts.productRequire = this.shuxingValue;
			}

			//加入到购物车列表中
			let cartList = this.$store.state.cartList;
			let isInclude = false; // 是否已经包含
			cartList.map(item => {
				let equal1 = item.productId === comboProducts.productId; // 产品id是否相等
				let equal2 = item.salePrice === comboProducts.salePrice; // 销售价格是否相等

				let desc1 = (item.productRequire || '') + (item.desc || '');
				let desc2 = (comboProducts.productRequire || '') + (comboProducts.desc || '');
				let equal3 = desc1 === desc2; // 产品描述是否相等

				let equal4 = (item.couponId || '') === this.couponId;

				if (equal1 && equal2 && equal3 && equal4) {
					isInclude = true;
					if (!this.isReplaceNum) {
						item.productCount += this.num;
					} else {
						item.productCount = this.num;
					}
				}
			});

			if (!isInclude) {
				cartList.push(comboProducts);
			}

			this.$store.commit('handleCartList', cartList);

			uni.showToast({
				title: '已加入'
			});

			this.closePop();

		}, true),

		// 关闭弹窗 && 重置数据
		closePop() {
			// 重置数据
			this.originTotalPrice = 0;
			this.totalPrice = 0;
			this.num = 1;
			this.relevanceProducts = [];
			this.relevanceMutexIds = {};
			this.relevanceSelects = [];
			this.shuxingConfig = {};
			this.shuxingValue = '';
			this.isReplaceNum = false;

			// 关闭弹窗
			this.$store.commit('handleShowSinglePop', false);
		}
	}
};
